﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fintech.Utils;
using ZOVNP.Engine;
using ZOVNP.Model.Abstracts;
using ZOVNP.WinView.Utils;

namespace ZOVNP.WinView
{
    internal class SellerCustomersTabPage : SellerTabPage
    {
        private DataGridView _dgvCustomers;

        public SellerCustomersTabPage(SellerMainControl mainControl) : base(mainControl)
        {
            Text = "Покупатели";
            Name = "tpCustomers";
        }

        protected override void InitializeInner()
        {
            _dgvCustomers = new DataGridView();
            _dgvCustomers.Name = "dgvCustomers";
            _dgvCustomers.Dock = DockStyle.Fill;
            this.Controls.Add(_dgvCustomers);

            CurrentCustomersContext = _mainControl.Workspace.Engine.CreateContext();

            _customers = new ExtendedBindingList<ICustomer>();
            _dgvCustomers.DataSource = _customers;
            _customers.ListChanged += CustomersListChanged;
            _customers.AddingNew += CustomersAddingNew;
            _dgvCustomers.RowLeave += DgvCustomersRowLeave;

            LoadCustomers();
        }

        public override void RefreshData()
        {
            LoadCustomers();
        }

        public override void Add()
        {
            //var customer = _mainControl.Workspace.CreateCustomer();
            //_customers.Add(customer);
        }

        public override void Delete()
        {
            if(_dgvCustomers.SelectedRows.Count > 0)
            {
                var selectedRows = _dgvCustomers.SelectedRows.Cast<DataGridViewRow>();
                selectedRows.ForEach(r => _customers.Remove((ICustomer)r.DataBoundItem));
            }
        }

        public override void Print()
        {

        }

        public override void Edit()
        {

        }

        private bool _customersInitializing = false;
        private bool _customersLoaded = false;

        private ExtendedBindingList<ICustomer> _customers;

        private IDomainContext _currentCustomersContext;

        private IDomainContext CurrentCustomersContext
        {
            get { return _currentCustomersContext; }
            set
            {
                if (_currentCustomersContext != null)
                    _currentCustomersContext.Dispose();

                _currentCustomersContext = value;
            }
        }

        public override void Save()
        {
            try
            {
                CurrentCustomersContext.SaveChanges();
            }
            catch(NotNullableFieldIsNullEntityExceptionException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadCustomers()
        {
            // Начинаем манипуляции со списком покупателей
            _customersInitializing = true;
            _customers.Clear();

            var customers = _mainControl.Workspace.GetAllCustomers();
            customers.ForEach(c =>
            {
                _customers.Add(c);
                CurrentCustomersContext.AttachObject(c);
            });

            // Закончили манипуляции со списком покупателей
            _customersInitializing = false;
        }

        private void DgvCustomersRowLeave(object sender, DataGridViewCellEventArgs e)
        {
            //Debug.WriteLine("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            //ExtendedBindingList<ICustomer> list = (ExtendedBindingList<ICustomer>)(((DataGridView)sender).DataSource);
            //var item = list[e.RowIndex];
            //if(item.CheckSelfProperties())
            //{
            //}
        }

        private void CustomersAddingNew(object sender, AddingNewEventArgs e)
        {
            e.NewObject = _mainControl.Workspace.CreateCustomer();
        }

        private void CustomersListChanged(object sender, ListChangedEventArgs e)
        {
            if (!_customersInitializing)
            {
                ExtendedBindingList<ICustomer> list = (ExtendedBindingList<ICustomer>)sender;
                switch (e.ListChangedType)
                {
                    case ListChangedType.Reset:
                        break;
                    case ListChangedType.ItemAdded:
                        {
                            var customer = list[e.NewIndex];
                            OnCustomerAdded(customer);
                        }
                        break;
                    case ListChangedType.ItemDeleted:
                        {
                            var args = (ExtendedListChangedEventArgs<ICustomer>)e;
                            var customer = args.Item;
                            OnCustomerDeleted(customer);
                        }
                        break;
                    case ListChangedType.ItemChanged:
                        {
                            var customer = list[e.NewIndex];
                            OnCustomerEdited(customer);
                        }
                        break;
                }
            }
        }

        private void OnCustomerAdded(ICustomer customer)
        {
            if (CurrentCustomersContext != null && customer.CheckSelfProperties())
            {
                CurrentCustomersContext.Add(customer);
            }
        }
        private void OnCustomerDeleted(ICustomer customer)
        {
            if (CurrentCustomersContext != null)
            {
                //if(customer.Context == null)
                //    CurrentContext.AttachObject(customer);

                CurrentCustomersContext.Delete(customer);
            }
        }
        private void OnCustomerEdited(ICustomer customer)
        {
            if (CurrentCustomersContext != null && customer.Context == null)
            {
                if (!customer.New)
                {
                    //CurrentContext.AttachObject(customer);
                    //customer.AddPhoneNumber = customer.AddPhoneNumber;
                }
                else
                {
                    //CurrentCustomersContext.Add(customer);
                    CurrentCustomersContext.Adder.AddCustomer(customer);
                }
            }
        }
    }
}
